
import { useCallback } from 'react';
import { t } from '@/locales/i18n';
import { message } from 'antd';
/**
 * copy text data
 */
export const useCopyData = () => {

  const hasHttps = () => {
    return window.location.protocol === 'https:';
  };
  const isProduction = false;

  const copyData = useCallback(
    async (
      data: string,
      title: string | null = t('common:common.Copy Successful'),
      duration = 1000
    ) => {
      data = data.trim();

      try {
        if ((hasHttps() || !isProduction) && navigator.clipboard) {
          await navigator.clipboard.writeText(data);
        } else {
          throw new Error('');
        }
      } catch (error) {
        // console.log(error);

        const textarea = document.createElement('textarea');
        textarea.value = data;
        textarea.style.position = 'absolute';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);

        textarea.select();
        const res = document.execCommand('copy');
        document.body.removeChild(textarea);

        if (!res) {
          // return toast({
          //   title: t('common:common.Copy_failed'),
          //   status: 'error',
          //   duration
          // });
          return message.error(t('common:common.Copy_failed'))
        }
      }

      if (title) {
        // toast({
        //   title,
        //   status: 'success',
        //   duration
        // });
        message.success('复制成功！')
      }
    },
    [t]
  );

  return {
    copyData
  };
};
